package com.ethan.ms.plugin.robot;

import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

import static com.ethan.ms.plugin.robot.Main.*;

public class ScriptAPI {

    public boolean serverAlertNotice(String msg) {
        return handleException("serverAlertNotice", () -> rmi.serverMessage(msg));
    }

    public String getAccountNameByQQ(long qq) {
        return handleException("getAccountNameByQQ", () -> {
            List<Map<String, Object>> list = rmi.customSqlResult("SELECT * FROM `accounts` WHERE `qq` = ?", qq);
            if (list.size() > 0) {
                return (String) list.get(0).get("name");
            }
            return null;
        }, String.class);
    }

    public boolean sendBroadcast(String msg){
        return handleException("sendBroadcast", () -> rmi.serverSpouseMessage(msg));
    }

    public boolean ban(String playerName) {
        return handleException("ban", () -> rmi.ban(playerName));
    }

    public boolean sendItemToAllOnlinePlayers(Map<Integer, Integer> items) {
        return handleException("sendItemToAllOnlinePlayers", () -> rmi.sendItemToAllOnlinePlayers(items));
    }

    public boolean sendItemToMap(int mapId, Map<Integer, Integer> items) {
        return handleException("sendItemToMap", () -> rmi.sendItemToMap(mapId, items));
    }

    public boolean sendItemToPlayer(String playerName, Map<Integer, Integer> items) {
        return handleException("sendItemToPlayer", () -> rmi.sendItemToPlayer(playerName, items));
    }

    public boolean disconnectPlayer(String playerName) {
        return handleException("disconnectPlayer", () -> rmi.disconnectPlayer(playerName));
    }

    public boolean addFame(String playerName, int fame) {
        return handleException("addFame", () -> rmi.addFame(playerName,fame));
    }

    public boolean changeRate(int type, int rate) {
        return handleException("changeRate", () -> rmi.changeRate(type,rate));
    }

    public boolean transferPlayer(String playerName, int distMapId) {
        return handleException("transferPlayer", () -> rmi.transferPlayer(playerName,distMapId));
    }

    public boolean customSqlInsert(String sql, Object... params) {
        return handleException("customSqlInsert", () -> rmi.customSqlInsert(sql, params));
    }

    public <T> T handleException(String apiName, Callable<T> callable, Class<T> tClass) {
        try {
            return callable.call();
        } catch (Exception e) {
            CQ.logError(apiName, e.toString());
            return null;
        }
    }

    public boolean handleException(String apiName, Callable<Boolean> callable) {
        try {
            return callable.call();
        } catch (Exception e) {
            CQ.logError(apiName, e.toString());
            return false;
        }
    }

}
